package fu.capstone.hanoicityguide.common.utility;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class DownloadFileFromURL extends AsyncTask<String, String, String> {
	String PATH = "/HCG/img";
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
//		showDialog(progress_bar_type);
	}

	@Override
	protected String doInBackground(String... f_url) {
		int count;
		try {
			for (int i = 0; i < f_url.length; i++) {
				URL url = new URL(f_url[i]);
				URLConnection conection = url.openConnection();
				conection.connect();
				// getting file length
				int lenghtOfFile = conection.getContentLength();

				// input stream to read file - with 8k buffer
				InputStream input = new BufferedInputStream(
						url.openStream(), 8192);
				System.out.println("Data::" + f_url[i]);
				// Create folder
				boolean success = true;
				File folder = new File(
						Environment.getExternalStorageDirectory(), PATH);
				if (!folder.exists()) {
					success = folder.mkdirs();
				}
				if (success) {
					System.out.print("SUCCESS");
				}
				// Output stream to write file
				OutputStream output = new FileOutputStream("sdcard/" + PATH
						+ "/image" + i + ".jpg");

				byte data[] = new byte[1024];

				long total = 0;

				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					// After this onProgressUpdate will be called
					publishProgress(""
							+ (int) ((total * 100) / lenghtOfFile));

					// writing data to file
					output.write(data, 0, count);
				}

				// flushing output
				output.flush();

				// closing streams
				output.close();
				input.close();
			}
		} catch (Exception e) {
			Log.e("Error: ", e.getMessage());
		}
		return null;
	}

	protected void onProgressUpdate(String... progress) {
		// setting progress percentage
//		pDialog.setProgress(Integer.parseInt(progress[0]));
	}

	/**
	 * After completing background task Dismiss the progress dialog
	 * **/
	@Override
	protected void onPostExecute(String file_url) {
		// dismiss the dialog after the file was downloaded
//		dismissDialog(progress_bar_type);

		// Displaying downloaded image into image view
		// Reading image path from sdcard
//		String imagePath = Environment.getExternalStorageDirectory()
//				.toString() + PATH + "/image0.jpg";

		// setting downloaded into image view
//		my_image.setImageDrawable(Drawable.createFromPath(imagePath));
	}
}
